package db

import (
	"github.com/jinzhu/gorm"
)

type IMMessage struct {
	gorm.Model

	RelateId uint
	FromId   uint
	ToId     uint
	Content  string
	Status   int

	TabName string `gorm:"-"` // 忽略字段
}

var messageArray = []*IMMessage{
	{TabName: "im_message_0"},
	{TabName: "im_message_1"},
	{TabName: "im_message_2"},
	{TabName: "im_message_3"},
	{TabName: "im_message_4"},
	{TabName: "im_message_5"},
	{TabName: "im_message_6"},
	{TabName: "im_message_7"},
}

var Message IMMessage

func messageDB(smallId, bigId uint) (*IMMessage, uint) {

	s := &IMSlave{}

	var id uint = 0
	if id = s.CheckHave(smallId, bigId, 0); id == 0 {
		return nil, 0
	}

	return messageArray[id%8], id
}

func (m *IMMessage) TableName() string {
	return m.TabName
}

func (*IMMessage) CheckFromId(msgId, fromId, toId uint, count int) (model []IMMessage) {

	m, relateId := messageDB(fromId, toId)

	if msgId != 0 {
		dbIns.Table(m.TableName()).
			Where("related_id=? and status=0 and id<=?", relateId, msgId).
			Order("created_at DESC").
			Limit(count).
			Find(&model)
	} else {
		dbIns.Table(m.TableName()).
			Where("related_id=? and status=0", relateId, msgId).
			Order("created_at DESC").
			Limit(count).
			Find(&model)
	}

	return
}

func (*IMMessage) CheckLastMsg(fromId, toId uint) (model IMMessage) {

	m, relateId := messageDB(fromId, toId)

	dbIns.Table(m.TableName()).
		Where("relate_id=?", relateId).
		Order("created_at DESC").
		Limit(1).
		First(&model)
	return
}

func (m *IMMessage) CheckById(msgId []uint) (model []IMMessage) {
	dbIns.Table(m.TableName()).
		Where("id in (?)", msgId).
		Find(&model)
	return
}

func (*IMMessage) Add(from, to uint, content string) (msgid uint) {

	m, id := messageDB(from, to)

	model := &IMMessage{
		RelateId: id,
		FromId:   from,
		ToId:     to,
		Content:  content,
	}

	dbIns.Table(m.TableName()).Save(model)

	return model.ID
}
